package top.javarem.medical.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import top.javarem.medical.common.constants.JwtClaimsConstant;
import top.javarem.medical.common.context.BaseContext;
import top.javarem.medical.common.utils.JwtProperties;
import top.javarem.medical.common.utils.JwtUtil;
import top.javarem.medical.domain.dto.*;
import top.javarem.medical.domain.po.User;
import top.javarem.medical.mapper.UserMapper;
import top.javarem.medical.service.UserService;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description 针对表【user(用户表)】的数据库操作Service实现
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private JwtProperties jwtProperties;

    @Override
    public LoginResponseDTO login(LoginDTO loginDTO) {

        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        //1、根据用户名查询数据库中的数据
        User user = this.lambdaQuery().eq(User::getUsername, username).one();
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            return null;
        }
        //密码比对
        //  后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            return null;
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        //3、返回
        return LoginResponseDTO.builder()
                .type(user.getType())
                .token(token)
                .build();
    }

    @Override
    public Boolean register(RegisterDTO registerDTO) {
        String username = registerDTO.getUsername();
        String password = registerDTO.getPassword();
        User user = this.lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        if (user != null) {
            return false;
        }
        String passwordAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        user = new User();
        user.setUsername(username);
        user.setPassword(passwordAsHex);
        String nickname = "药友" + RandomStringUtils.randomNumeric(4);
        user.setNickname(nickname);
        user.setType(0);  //用户Type值是0
        user.setPoints(0);
        user.setAvatar("https://p2.ssl.qhimgs1.com/t046a6660d4c39bc75e.jpg");
        return this.save(user);
    }

    @Override
    public List<UserDTO> queryAllUser() {

        if (isNotRoot())
            return null;
        List<User> userList = lambdaQuery()
                .eq(User::getType, 0)
                .list();
        List<UserDTO> userDTOList = new ArrayList<>();
        for (User user : userList) {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            userDTOList.add(userDTO);
        }
        return userDTOList;


    }

    @Override
    public Boolean updateUser(UserDTO userDTO) {

        if (isNotRoot())
            return false;

        return lambdaUpdate()
                .set(User::getNickname, userDTO.getNickname())
                .set(User::getAvatar, userDTO.getAvatar())
                .set(User::getPoints, userDTO.getPoints())
                .set(User::getStatus, userDTO.getStatus())
                .eq(User::getId, userDTO.getId())
                .update();
    }

    @Override
    public UserDetailDTO queryUserDetail(UpdateUserInfoDTO updateUserInfoDTO) {

        Long userId;
        if (isNotRoot()) {
            userId = BaseContext.<Long>getCurrentId();

        } else {
            userId = updateUserInfoDTO.getId();
        }
        User user = lambdaQuery()
                .select(User::getId, User::getNickname, User::getAvatar, User::getPoints, User::getType, User::getUsername, User::getPassword, User::getStatus)
                .eq(User::getId, userId)
                .one();
        if (user == null) {
            return null;
        }
        UserDetailDTO userDetailDTO = new UserDetailDTO();
        BeanUtils.copyProperties(user, userDetailDTO);
        return userDetailDTO;


    }

    @Override
    public Boolean updateUserInfo(UpdateUserDTO updateUserInfoDTO) {

        Long userId = BaseContext.<Long>getCurrentId();

        return lambdaUpdate()
                .set(User::getNickname, updateUserInfoDTO.getNickname())
                .set(User::getAvatar, updateUserInfoDTO.getAvatar())
                .eq(User::getId, userId)
                .update();
    }

    //判断当前用户是不是管理员
    public boolean isNotRoot() {
        Long userId = BaseContext.<Long>getCurrentId();
        User root = lambdaQuery()
                .eq(User::getId, userId)
                .eq(User::getType, 1)
                .one();
        return root == null;
    }

}
